package com.xyz.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 夏永泽
 * @date 2022/1/10
 */
public class JwtUtils {
    private final static String SECRET = "9bb956029d21c4c81421992795e77c6897a4c02921711b63a55fbbe53185cec1";
    private final static Long EXPIRE_TIME = TimeUnit.DAYS.toMillis(7);

    public static String getToken(String name, Integer role, String idNumber) {
        // jwt生成时间 当前时间
        final long nowMillis = System.currentTimeMillis();
        final Date date = new Date(nowMillis);

        final HashMap<String, Object> claims = new HashMap(2) {
            {
                put("name", name);
                put("role", role);
                put("idNumber", idNumber);
            }
        };

        return Jwts.builder()
                .setClaims(claims)
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(date)
                .setExpiration(new Date(nowMillis + EXPIRE_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET.getBytes())
                .compact();
    }

    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET.getBytes())
                .parseClaimsJws(token)
                .getBody();
    }

    public static boolean verify(String token) {
        try {
            parseToken(token);
        } catch (Exception e) {
            // Usually SignatureException
            return false;
        }
        return true;
    }
}
